import { defineStore } from 'pinia'
import { useCookies } from '@vueuse/integrations/useCookies'
import { usePermissionStore, useTagsViewStore, store } from '../index'
import userAvatar from '@/assets/img/avatar.jpg'
import { resetRouter } from '@/router'

const cookies = useCookies(['locale'])

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    token: cookies.get('token'),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  }),
  getters: {
    getToken() {
      return this.token
    },
    getRoles() {
      return this.roles
    }
  },
  actions: {
    getUserInfo() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const res = {
            username: 'Admin',
            avatar: '',
            roles: [],
            permissions: []
          }
          this.name = res.username
          this.avatar = res.avatar ? res.avatar : userAvatar

          if (res.roles?.length > 0) { // 验证返回的roles是否是一个非空数组
            this.roles = res.roles
            this.permissions = res.permissions
          } else {
            this.roles = ['ROLE_DEFAULT']
          }
          resolve(res)
        }, 50)
      })
    },
    // 登录
    login({ username, password }) {
      console.log(username, password)
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const res = {
            token: 'eyJpZCI6IjllZDU3NDBmLTFiOGItNTQ1ZC1iNjUzLTg2NmU0NjE5ZGVkYiIsImNyZWF0ZWQiOjE2NTY2Mzg3MzA3MDgsImV4aXN0aW5nIjpmYWxzZX0='
          }
          this.token = res.token
          cookies.set('token', res.token)
          resolve(res)
        }, 50)
      })
    },
    // 退出登录
    logout() {
      return new Promise((resolve, reject) => {
        const permissionStore = usePermissionStore()
        const tagsViewStore = useTagsViewStore()
        setTimeout(() => {
          cookies.remove('token')
          this.$reset()
          permissionStore.$reset()
          tagsViewStore.$reset()
          resetRouter()
          resolve()
        }, 50)
      })
    }
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
